package com.zh.jbet.core.service;

import com.zh.jbet.core.dao.BetContextDao;
import com.zh.jbet.core.dao.BetDao;
import com.zh.jbet.core.dao.GameDao;
import com.zh.jbet.core.dao.PlayerGameDao;
import com.zh.jbet.core.dto.BetTable;
import java.util.List;

import com.zh.jbet.core.entity.Bet;
import com.zh.jbet.core.entity.BetContextEntity;
import com.zh.jbet.core.entity.BetScorers;
import com.zh.jbet.core.entity.Game;
import com.zh.jbet.core.entity.GameContext;
import com.zh.jbet.core.entity.PlayerGame;
import com.zh.jbet.core.scorer.GameScorer;
import javax.swing.tree.DefaultMutableTreeNode;

public class BetService<T extends Game> {

    private List<BetDao<? extends Bet>> betDaos;
    private GameDao<T> gameDao;
    private BetContextDao betContextDao;
    private PlayerGameDao playerGameDao;

    public BetTable loadBets(BetContextEntity bet) {
        return null;
    }

    /**
     * Calculate bet points after finished a game
     * @param gameContext
     * @param game
     */
    public void finishGame(GameContext context, DefaultMutableTreeNode gameNode) {
        T game = (T) gameNode.getUserObject();
        List<PlayerGame> pgames = playerGameDao.loadAllContextGames(context);
        for (PlayerGame pge: pgames) {
            BetScorers<T> scorers = pge.getGameScorer(gameDao.getEntityClass());
            for (BetDao betDao: betDaos) {
                updateAllBet(betDao, scorers.getScorer(betDao.getEntityClass()), game, game.getId());
            }
        }
    }


    private <U extends Bet> void updateAllBet(BetDao<U> betDao, GameScorer<T,U> scorer, T game, Long playerGameId) {
        List<U> bets = betDao.findAllBets(game.getId(), playerGameId);
        for (U b: bets) {
            int score = scorer.score(game, b);
            b.setPoint(score);
            betContextDao.updateContext(b);
        }
    }


    public void addGame(GameContext gameContext, T game) {
    }

    /**
     * Open the game to players
     * @param gameContext
     */
    public void openGame(GameContext gameContext) {
    }
}
